<template>
  <div class="product-selector">
    <el-select
      v-model="currentProduct"
      placeholder="选择产品"
      size="default"
      style="width: 200px"
      @change="handleProductChange"
      :loading="loading"
    >
      <el-option
        v-for="product in products"
        :key="product.id"
        :label="product.fullLabel"
        :value="product.id"
      >
        <div class="product-option">
          <span class="product-name">{{ product.name }}</span>
          <span class="product-version" v-if="product.version"> {{ product.version }}</span>
        </div>
      </el-option>
    </el-select>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useAppStore } from '@/stores/app'
import { productApi } from '@/api/products'

const appStore = useAppStore()

// 响应式数据
const loading = ref(false)

// 计算属性
const products = computed(() => {
  // 确保products是数组，并且格式正确
  const productsData = appStore.products || []
  if (!Array.isArray(productsData)) {
    console.warn('Products data is not an array:', productsData)
    return []
  }

  // 将数组格式转换为对象格式
  return productsData.map(productArray => {
    // 假设数组格式为: [id, name, version, ...]
    const id = productArray[0] || ''
    const name = productArray[1] || ''
    const version = productArray[2] || ''

    return {
      id,
      name,
      version,
      fullLabel: version ? `${name} ${version}` : name,
      components: productArray.slice(3) || []
    }
  })
})

const currentProduct = computed({
  get: () => appStore.currentProduct,
  set: (value) => appStore.setCurrentProduct(value)
})

// 方法
const handleProductChange = (productId) => {
  console.log('Product changed to:', productId)

  // 根据productId查找对应的产品信息
  const selectedProduct = products.value.find(p => p.id === productId)
  if (selectedProduct) {
    console.log('Setting product info:', {
      productId: selectedProduct.id,
      productName: selectedProduct.name,
      version: selectedProduct.version
    })

    // 使用产品名称和版本设置store
    appStore.setCurrentProduct(selectedProduct.name, selectedProduct.version)
  } else {
    console.warn('Product not found for ID:', productId)
  }
}

const loadProducts = async () => {
  loading.value = true
  try {
    const response = await productApi.getProducts()
    // 修复：正确提取data数组
    const productsData = response.data?.data || []
    console.log('Products loaded:', productsData)
    appStore.setProducts(productsData)
  } catch (error) {
    console.error('Failed to load products:', error)
    // 出错时设为空数组
    appStore.setProducts([])
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(() => {
  loadProducts()
})
</script>

<style lang="scss" scoped>
.product-selector {
  .product-option {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .product-name {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .product-version {
      font-size: 12px;
      color: var(--el-text-color-secondary);
      margin-left: 8px;
    }
  }
}
</style>